import 'dart:async';

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class AppLocalNotificationService {
  static const String channelId = "my_salary_channer_id";
  static const String channelName = "my_salary_channer_name";
  static const String channelDescription = "my_salary_channer_desc";

  static final FlutterLocalNotificationsPlugin notificationsPlugin =
      FlutterLocalNotificationsPlugin();

  static Future<void> init() async {
    // 初始化通知插件
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    await notificationsPlugin.initialize(
        const InitializationSettings(android: initializationSettingsAndroid));

    await _initNotifications();
  }

  static Future<void> _initNotifications() async {
    const AndroidNotificationChannel channel = AndroidNotificationChannel(
      channelId,
      channelName,
      description: channelDescription,
      importance: Importance.high,
    );

    await notificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);
  }

  // 该方式和MainActivity效果一致
  static Future<void> showNotification(Map<String, dynamic> message) async {
    const AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(
      channelId,
      channelName,
      channelDescription: channelDescription,
      importance: Importance.max,
      priority: Priority.high,
      showWhen: false,
    );

    await notificationsPlugin.show(
      message.hashCode,
      message['title'] ?? '新消息',
      message['alert'] ?? '你有新消息',
      const NotificationDetails(
        android: androidPlatformChannelSpecifics,
      ),
      payload: message.toString(),
    );
  }

  static Future<void> handleNotificationClick(
      Map<String, dynamic> message) async {
    //todo:
  }
}
